package com.woniu.controller;

import com.google.code.kaptcha.Producer;
import com.woniu.entity.Result;
import com.woniu.entity.dto.LoginAdminDTO;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * 生成图片验证码
 *
 * @author 狐狸半面添
 * @create 2023-01-29 17:35
 */
@RestController
@RequestMapping
public class CaptchaServiceController extends BaseController{
    @Resource
    private Producer producer;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取修改密码的图片验证码base64编码
     * 并缓存至redis中
     *
     * @return base编码
     */
    @GetMapping("/captchaImage")
    public Result getPwdCaptcha(HttpSession session){
        // 1.生成验证码字符
        String text = producer.createText().toLowerCase();
        // 2.生成图片
        BufferedImage bi = producer.createImage(text);
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        try {
            ImageIO.write(bi, "jpg", fos);
            // 3.缓存至 redis 中
            session.setAttribute("code",text);
            // 4.返回验证码图片的base64编码
            String imgEncode = Base64.encodeBase64String(fos.toByteArray());
            fos.flush();
            return toDataResult(imgEncode);
        }catch (Exception e){
            return error();
        }finally {
            fos.close();
        }
    }

    @GetMapping("/getCode")
    public Result getCode(HttpSession httpSession){
        String code = httpSession.getAttribute("code").toString();
        System.out.println("code = " + code);
        return toDataResult(code);
    }
}
